#!/usr/bin/env bash
set -e
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
# Function :CentOS7.X 二进制安装mysql
# Platform :RedHatEL7.x Based Platform
# Version  :1.01
# Date     :2022-10-14
# Author   :mugoLH
# Contact  :hxsaj@126.com
# Company  :liando
# depend on:
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

#  脚本引用 Import the script
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

#  变量列表 List of common variables
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

# 已被此脚本位置参数2代替
#Downloads_bin_file_address="https://mirrors.ustc.edu.cn/mysql-ftp/Downloads/MySQL-5.7/mysql-5.7.38-linux-glibc2.12-x86_64.tar.gz"
# 已被此脚本位置参数1代替
#install_dir="/data"


#  函数列表 Function list
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

# 检查wget命令
function wget_chack(){
	if [[ $(whereis wget | wc -l) -ne 1 ]];then
		echo -e "[ 安装wget ]: " && yum -y -q install wget
	fi
}
# 下载 mysql 二进制文件
function wget_download(){
	Download_URL=${1}
	if [[ $(whereis wget | wc -l) -eq 1 ]];then
		echo -e "[ 下载文件 ]：" && wget -c ${Download_URL} --no-check-certificate
	else
		wget_chack
	fi
}
# 安装 mysql 二进制文件
function mysql_install(){
	install_dir=${1}
	server_port=${2}
	BintarFile_or_DownloadURL=${3}

	if [[ $# -eq 3 ]];then
		if [[ ! -d ${install_dir} ]];then
			echo -e "创建安装目录：${install_dir}"
			mkdir -p ${install_dir}
		fi

		if [[ -f ${BintarFile_or_DownloadURL} ]];then
			Bin_tar_file=${BintarFile_or_DownloadURL}
		else
			if [[ $(curl -I -m 10 -o /dev/null -s -w %{http_code} ${BintarFile_or_DownloadURL} ) -eq 200 ]];then
				# 下载 mysql 二进制文件
				wget_chack
				wget_download ${BintarFile_or_DownloadURL}
				# 确定下载文件的的名字
				Bin_tar_file=$(echo "${BintarFile_or_DownloadURL}" | awk -F "/" '{print$NF}')
			else
				echo -e "不是tar.gz压缩包 或 文件下载URL错误！"
				exit 2
			fi
		fi
		# 解压二进制到指定目录
		echo -e "[ 解压文件 ]: ${install_dir}" && tar -zxf ${Bin_tar_file} -C ${install_dir}/

		# 修改目录名字，便于使用
		Bin_Basename=$(tar -ztf ${Bin_tar_file} | head -5 | awk -F "/" '{print$1}' |sort -nr |uniq)
		Base_Mysql=$(echo ${Bin_Basename} |awk -F "-" '{print$1"-"$2}')
		mv ${install_dir}/${Bin_Basename} ${install_dir}/${Base_Mysql}_${server_port}

		# 创建配置目录和数据目录
		mkdir -p ${install_dir}/${Base_Mysql}_${server_port}/{data,conf}

		# 生成配置文件
		echo -e "[ 生成配置 ]：${install_dir}/${Base_Mysql}_${server_port}/conf/my.cnf "
		cat > ${install_dir}/${Base_Mysql}_${server_port}/conf/my.cnf << EOF
[client]
default-character-set  = utf8mb4

[mysql]
port                   = ${server_port}
socket                 = ${install_dir}/${Base_Mysql}_${server_port}/data/mysql.sock
default-character-set  = utf8mb4

[mysqld]
port                   = ${server_port}
default_storage_engine = InnoDB
basedir                = ${install_dir}/${Base_Mysql}_${server_port}
datadir                = ${install_dir}/${Base_Mysql}_${server_port}/data
socket                 = ${install_dir}/${Base_Mysql}_${server_port}/data/mysql.sock
character-set-client-handshake = FALSE
character-set-server   = utf8mb4
collation-server       = utf8mb4_unicode_ci
init_connect           = 'SET NAMES utf8mb4'
max_connections        = 2000
max_allowed_packet     = 128M
innodb_file_per_table  = 1
tmp_table_size         = 134217728
max_heap_table_size    = 134217728
lower_case_table_names = 1

log-bin                = mysql-bin
max_binlog_size        = 1024M
expire_logs_days       = 1
log_slave_updates      = 1
server-id              = 1

sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

EOF

		# 创建运行账号
		if ! id mysql >/dev/null 2>&1;then
			useradd mysql
		fi

		# 授权相关目录权限
		chown -R mysql.mysql ${install_dir}

		# 写入环境变量
		echo -e "[ 环境变量 ]：/etc/bashrc"
		echo -e "export PATH=${install_dir}/${Base_Mysql}_${server_port}/bin:\$PATH" >> /etc/bashrc

		# 环境变量生效
		source /etc/bashrc

		# 软连接sock文件
		ln -s ${install_dir}/${Base_Mysql}_${server_port}/data/mysql.sock /tmp/mysql_${server_port}.sock

		# 初始化 mysql
		echo -e "[ 初始服务 ]:"
		mysqld --defaults-file=${install_dir}/${Base_Mysql}_${server_port}/conf/my.cnf --user=mysql --initialize > /tmp/${Base_Mysql}_${server_port}.install.tmp 2>&1

		# 启动mysql
		echo -e "[ 启动mysql]: ${install_dir}/${Base_Mysql}_${server_port}/bin/mysqld_safe --defaults-file=${install_dir}/${Base_Mysql}_${server_port}/conf/my.cnf --user=mysql &"
		${install_dir}/${Base_Mysql}_${server_port}/bin/mysqld_safe --defaults-file=${install_dir}/${Base_Mysql}_${server_port}/conf/my.cnf --user=mysql > /dev/null 2>&1 &

		# 修改初始密码
		sleep 5
		${install_dir}/${Base_Mysql}_${server_port}/bin/mysql -uroot -p$(awk '/root@localhost/{print$NF}' /tmp/${Base_Mysql}_${server_port}.install.tmp) --connect-expired-password --socket=${install_dir}/${Base_Mysql}_${server_port}/data/mysql.sock -sNe "set password = password('594hxs');" 2>/dev/null
		echo -e "[ 部署完成 ]: 数据库root密码：594hxs，请执行: source /etc/bashrc && mysql -uroot -p594hxs --socket=${install_dir}/${Base_Mysql}_${server_port}/data/mysql.sock  登录数据库执行计划操作！"
	fi
}


if [[ $# -eq 3 ]];then
	install_dir=${1}
	server_port=${2}
	BintarFile_or_DownloadURL=${3}
	mysql_install ${install_dir} ${server_port} "${BintarFile_or_DownloadURL}"
else
	echo -e "[ 使用方法 ]：$0 \"[安装位置{字符串}]\" \"端口\" \"[下载二进制的URL地址 | 二进制压缩包绝对路径]\""
fi
